# 迭代器：一次只返回一个元素，省内存，只能自行通过调用next方法，才能返回值。
# 迭代器中没有值后抛出的异常需要自行处理

# 生成器：特殊的迭代器，通过生成器可以实现函数的暂停。
# yield：暂停并返回右边的值

# 协程：函数的实现依靠：send赋值，yield暂停并返回值
# send->yield；send->yield；send->yield

# asyncio：将事件放入一个队列中，通过对队列的循环实现事件的异步访问

# 协程实现计算平均数
def get_avg():
    sum = 0
    num = 0
    while True:
        # value = yield sum / num
        try:
            value = yield sum / num
        except ZeroDivisionError:
            value = yield 0
        sum += value
        num += 1

my_avg = get_avg()
print(next(my_avg))
print(my_avg.send(4))
print(my_avg.send(12))
# 0
# 4.0
# 8.0



# asyncio
import asyncio

class Response:
    ststus_code = 1

async def sim_request(index):
    print(f"模拟发送请求 Index: {index}")
    response = Response()
    print("将休眠3秒")
    await asyncio.sleep(3)
    print(f"request index {index}, response status_code: {response.ststus_code}")
    # 尝试返回一个递增列表
    return response.ststus_code+index

loop = asyncio.get_event_loop()

task_array = []
for i in range(10):
    print("在这里尝试打印")
    task_array.append(sim_request(i))
    print("我又在这尝试打印")

# loop.run_until_complete(asyncio.wait(task_array))
result = loop.run_until_complete(asyncio.gather(*task_array))
print(result)

loop.close()